import { registerDecorator, ValidationOptions, ValidationArguments } from "class-validator";

// * 自定义身份证校验装饰器
export const IsIdCard = (property: string, validationOptions?: ValidationOptions) => {
  return (object: Object, propertyName: string) => {
    registerDecorator({
      name: "isIdCard",
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(_, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints; // key
          const relatedValue = (args.object as any)[relatedPropertyName]; // value
          const regular = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
          if (regular.test(relatedValue)) return true;
          return false;
        },
      },
    });
  };
};

// * 自定义身份证校验装饰器
export const IsPhone = (property: string, validationOptions?: ValidationOptions) => {
  return (object: Object, propertyName: string) => {
    registerDecorator({
      name: "isPhone",
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints;
          const relatedValue = (args.object as any)[relatedPropertyName];
          const regular = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
          if (regular.test(relatedValue)) return true;
          return false;
        },
      },
    });
  };
};
